package ca.uwindsor;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import android.app.AlertDialog;
import android.app.ExpandableListActivity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.SimpleExpandableListAdapter;

public class ViewSchedule extends ExpandableListActivity {
List<String> childList = new ArrayList<String>(); //used to store child data.
Common common = new Common();	
HashMap<String, String> idArray = new HashMap<String, String>(); //stores the id of the table row to access later

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		//set window title to sem name
		//requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		//getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.view_schedule);
		//getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.summary);
		//TextView lblSemName = (TextView)findViewById(R.id.lblSemName);
		//lblSemName.setText(Common.globalTerm);
		//TODO:
		//Summary here
		
		 //Create Expandable lists
		SimpleExpandableListAdapter expListAdapter =
				new SimpleExpandableListAdapter(
					this,
					createGroupList(),	// groupData describes the first-level entries
					R.layout.child_row,	// Layout for the first-level entries
					new String[] { "date" },	// Key in the groupData maps to display
					new int[] { R.id.lblDay },		// Data under "Day" key goes into this TextView
					createChildList(),	// childData describes second-level entries
					R.layout.child_row,	// Layout for second-level entries
					new String[] { "course", "type" },	// Keys in childData maps to display
					new int[] { R.id.lblDay, R.id.lblTime }	// Data under the keys above go into these TextViews
				);
			setListAdapter( expListAdapter );
		getExpandableListView().setOnChildClickListener(this);
		
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		finish();
	}

	//for menu do not change
	@Override
	public boolean onCreateOptionsMenu(Menu menu){
		super.onCreateOptionsMenu(menu);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.main_menu, menu);
		return true;
	}
	
	//Creates the Day list and returns
	private List<HashMap<String, String>> createGroupList() {
		
		final MyDBAdapter db = new MyDBAdapter(getApplicationContext());
		db.setDATABASE_TABLE("event_schedule");
		db.open();
		
		String[] columnName = {"Date"};
		Cursor ret = db.getDistinct(columnName);
		
		//get distinct dates
		
		ArrayList<HashMap<String, String>> result = new ArrayList<HashMap<String, String>>();
		 
		if(ret.moveToFirst()){
			do{
				//populate the list
				
				Date date = common.StringToDate(ret.getString(0));
				HashMap<String, String> m = new HashMap<String, String>();
			    m.put( "date", common.DateToString(date,"E d MMM y"));
				result.add( m );
				
				
				//create child list
				
				
				childList.add(ret.getString(0));
				
				
			}while(ret.moveToNext());
		}
		db.close();
		
		  return (List<HashMap<String, String>>)result;
	    }
	
	//Create the child list. Passed in the course list
	private List<ArrayList<HashMap<String, String>>> createChildList() {
		final MyDBAdapter db = new MyDBAdapter(getApplicationContext());
		db.setDATABASE_TABLE("event_schedule");
		db.open();
		
		Iterator<String> listiter = childList.iterator();
		
		ArrayList<ArrayList<HashMap<String, String>>> result = new ArrayList<ArrayList<HashMap<String, String>>>();
		
		
		while(listiter.hasNext()){
		
		Cursor ret_sch = db.getEntry("Date",listiter.next() );
		ArrayList<HashMap<String, String>> secList = new ArrayList<HashMap<String, String>>(); //VOILA!!!!
		
		if(ret_sch.moveToFirst()){
			do{
				
				 	HashMap<String, String> child = new HashMap<String, String>();
					child.put( "course", ret_sch.getString(2));
				    child.put( "type", ret_sch.getString(5)+" "+ ret_sch.getString(3)+"  to  "+ret_sch.getString(4) );
					secList.add( child );
					idArray.put((result.size())+""+(secList.size()-1), ""+ret_sch.getInt(0));

			}while(ret_sch.moveToNext());
			 result.add( secList );
			 
		}
		ret_sch.close();
	//add sub list to main list
		}
		 db.close();
		 
		return (List<ArrayList<HashMap<String, String>>>) result;
	  }
	
	
	//for menu do not change
	@Override
	public boolean onOptionsItemSelected(MenuItem item){
		
		switch(item.getItemId())
		{
		case R.id.menuaddcourse:
			startActivity(new Intent ("ca.uwindsor.ADDCOURSES"));
			return true;
		case R.id.menuaddclass:
			startActivity(new Intent ("ca.uwindsor.ADDSCHEDULE"));
			return true;
		case R.id.menuaddassm:
			startActivity(new Intent ("ca.uwindsor.ADDASSM"));
			return true;
		case R.id.viewschedule:
			startActivity(new Intent ("ca.uwindsor.VIEWSCHEDULE"));
			return true;
		}
		return false;
		
	}
	
	@Override
	public boolean onChildClick(ExpandableListView parent, View v,  int groupPosition,
	         int childPosition, long id) {
	    // use groupPosition and childPosition to locate the current item in the adapter
		
		//String groupName =(String)mAdapter.getGroup(groupPosition);
		
		final AlertDialog.Builder alert = new AlertDialog.Builder(this);
		
		
		final ExpandableListAdapter mAdapter = parent.getExpandableListAdapter();

		//alert.setMessage(""+);
		final int inGroupPos = groupPosition;
		final int inChildPos = childPosition;
		
		
		alert.setMessage("Mark as done?");
		
		
		alert.setPositiveButton("Yes", new OnClickListener() {
			
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				final MyDBAdapter db = new MyDBAdapter(getApplicationContext());
				db.setDATABASE_TABLE("event_schedule");
				db.open();
				if(db.removeEntry("_id",idArray.get(mAdapter.getGroupId(inGroupPos)+""+mAdapter.getChildId(inGroupPos, inChildPos))))
				{
					final AlertDialog.Builder alert2 = new AlertDialog.Builder(ViewSchedule.this);
					alert2.setMessage("Event marked as done.");
					alert2.setNegativeButton("OK", new DialogInterface.OnClickListener() {

						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							startActivity(new Intent("ca.uwindsor.VIEWSCHEDULE"));
						}

					});
					alert2.setCancelable(false);
					alert2.show();
					
				}
				db.close();
			}
		});
		

		alert.setNegativeButton("No", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				
			}

		});
		
		//Give choice to edit.
		alert.setNeutralButton("Edit", new OnClickListener() {
			
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				Intent intent = new Intent("ca.uwindsor.EDITASSM");
				//send id to edit schedule
				int _id = Integer.parseInt(idArray.get(mAdapter.getGroupId(inGroupPos)+""+mAdapter.getChildId(inGroupPos, inChildPos)));
				intent.putExtra("_id",_id );
				startActivity(intent);
			}
		});
		
		
		alert.setCancelable(false);
		alert.show();
		
	
	    return true;
	}

}
